import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { message } from 'ant-design-vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/PublicArticles.vue')
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/ProfilePage.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/resume',
    name: 'ResumePage',
    component: () => import('@/views/ResumePage.vue')
  },
  {
    path: '/article/:id',
    name: 'ArticleDetail',
    component: () => import('@/views/ArticleDetail.vue')
  },
  {
    path: '/category/:id',
    name: 'CategoryPage',
    component: () => import('@/views/CategoryPage.vue')
  },
  {
    path: '/tag/:id',
    name: 'TagPage',
    component: () => import('@/views/TagPage.vue')
  },
  {
    path: '/categories',
    name: 'CategoriesIndex',
    component: () => import('@/views/CategoriesIndex.vue')
  },
  {
    path: '/tags',
    name: 'TagsIndex',
    component: () => import('@/views/TagsIndex.vue')
  },
  {
    path: '/hot',
    name: 'HotPage',
    component: () => import('@/views/HotPage.vue')
  },
  {
    path: '/archives',
    name: 'ArchivesPage',
    component: () => import('@/views/ArchivesPage.vue')
  },
  {
    path: '/search',
    name: 'SearchPage',
    component: () => import('@/views/SearchPage.vue')
  },
  {
    path: '/admin',
    component: () => import('@/layouts/AdminLayout.vue'),
    children: [
      { path: 'articles', name: 'AdminArticles', component: () => import('@/views/ArticlesList.vue'), meta: { requiresAuth: true } },
      { path: 'categories', name: 'AdminCategories', component: () => import('@/views/AdminCategories.vue'), meta: { requiresAuth: true, requiredPerm: 'category:manage' } },
      { path: 'tags', name: 'AdminTags', component: () => import('@/views/AdminTags.vue'), meta: { requiresAuth: true, requiredPerm: 'tag:manage' } },
      { path: 'comments', name: 'AdminComments', component: () => import('@/views/AdminComments.vue'), meta: { requiresAuth: true, requiredPerm: 'comment:manage' } },
      { path: 'resume', name: 'AdminResume', component: () => import('@/views/AdminResume.vue'), meta: { requiresAuth: true, requiredPerm: 'resume:manage' } },
      { path: 'oss', name: 'AdminOss', component: () => import('@/views/AdminOss.vue'), meta: { requiresAuth: true, requiredPerm: 'oss:manage' } },
      { path: 'user-roles', name: 'AdminUserRoles', component: () => import('@/views/AdminUserRoles.vue'), meta: { requiresAuth: true, requiredPerm: 'user:manage' } },
      { path: 'users', name: 'AdminUsers', component: () => import('@/views/AdminUsers.vue'), meta: { requiresAuth: true, requiredPerm: 'user:manage' } },
      { path: 'roles', name: 'AdminRoles', component: () => import('@/views/AdminRoles.vue'), meta: { requiresAuth: true, requiredPerm: 'role:manage' } },
      { path: 'permissions', name: 'AdminPermissions', component: () => import('@/views/AdminPermissions.vue'), meta: { requiresAuth: true, requiredPerm: 'permission:manage' } },
      { path: 'oplogs', name: 'AdminOpLogs', component: () => import('@/views/AdminOpLogs.vue'), meta: { requiresAuth: true, requiredPerm: 'permission:manage' } },
      { path: 'settings', name: 'AdminSettings', component: () => import('@/views/AdminSettings.vue'), meta: { requiresAuth: true, requiredPerm: 'permission:manage' } },
      { path: 'sessions', name: 'AdminSessions', component: () => import('@/views/AdminSessions.vue'), meta: { requiresAuth: true, requiredPerm: 'user:manage' } },
      { path: 'article-assets', name: 'AdminArticleAssets', component: () => import('@/views/AdminArticleAssets.vue'), meta: { requiresAuth: true } },
      { path: 'api-docs', name: 'AdminApiDocs', component: () => import('@/views/AdminApiDocs.vue'), meta: { requiresAuth: true, requiredPerm: 'permission:manage' } },
      { path: 'permission-test', name: 'AdminPermissionTest', component: () => import('@/views/AdminPermissionTest.vue'), meta: { requiresAuth: true } },
      { path: '', redirect: { name: 'AdminArticles' } }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: {
      template: '<div style="max-width:960px;margin:24px auto;padding:12px"><h2>页面未找到</h2><p>您访问的地址不存在。</p><p><router-link to="/">返回首页</router-link></p></div>'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

router.beforeEach((to) => {
  if (to.matched.some(r => (r.meta as any)?.requiresAuth)) {
    const token = localStorage.getItem('token')
    if (!token) {
      message.warning('请先登录再访问管理页面')
      return { path: '/' }
    }
    const requiredPerm = (to.meta as any)?.requiredPerm as string | undefined
    if (requiredPerm) {
      try {
        const cached = localStorage.getItem('profile')
        const perms = cached ? (JSON.parse(cached).perms as string | undefined) : undefined
        if (perms && perms.length) {
          const set = new Set(perms.split(',').map((s: string) => s.trim()).filter(Boolean))
          if (!set.has(requiredPerm)) {
            message.warning('没有访问该页面的权限')
            return { path: '/admin' }
          }
        }
      } catch {}
    }
  }
  return true
})

export default router


